﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jurassic.Library;
using Jurassic;
using Flower.Services;
using Flower.Directory.Host;
using Flower.Services.Data;

namespace Flower.Directory.Scripting.Functions.Processes
{
    internal class SelectProcessor : ClrFunction
    {
        public SelectProcessor(ScriptEngine engine)
            : base(engine.Function.InstancePrototype, "__selectProcessor", engine.Function.InstancePrototype)
        {
        }

        [JSCallFunction]
        public string Exec(string workflow)
        {
            try
            {
                var result = Exec(Engine.GetDirectory(), workflow);

                return (result != null) ? (string)result["processor"] : null;
            }
            catch (JavaScriptException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new JavaScriptException(Engine, "Error", ex.Message, ex);
            }
        }

        [ClrScript]
        public static Dictionary<string, object> Exec(IDirectory dir, string workflow)
        {
            var processDispatcherHolder = dir as IProcessesDispatcherHolder;
            IProcessesDispatcher dispatcher;

            if (processDispatcherHolder == null || (dispatcher = processDispatcherHolder.ProcessesDispatcher) == null)
            {
                IList<DirectoryEntryInfo> activeProcessors =
                    dir.GetChildrenInfo
                    (
                        "/Processors/Active",
                        DirectoryEntryTypes.Link,
                        SortProperty.Default,
                        SortOrder.Asc,
                        0,
                        1
                    );

                return (activeProcessors.Count > 0) ? new Dictionary<string, object> { { "processor", activeProcessors[0].Name } } : null;
            }
            else
            {
                return new Dictionary<string, object> { { "processor", dispatcher.SelectProcessor(workflow) } };
            }
        }
    }
}
